package com.shirodemo.realm;

import com.shirodemo.pojo.Role;
import com.shirodemo.pojo.User;
import com.shirodemo.service.RoleService;
import com.shirodemo.service.UserService;
import com.shirodemo.util.ColUtil;
import com.shirodemo.util.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by 追风少年
 *
 * @email doubihah@foxmail.com
 * @create 2017/12/13 13:03
 **/
@Component
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    /**
     * 获取授权信息
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 登录验证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 基于用户名和密码的令牌
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername(); // 用户名
        if(!StringUtils.isNull(username)){
            User user = userService.findByUsername(username);
            if(user == null) {
                throw new UnknownAccountException();//没找到帐号
            }
            if(user.getLocked()) {
                throw new LockedAccountException(); //帐号锁定
            }
            if(user != null){
                return new SimpleAuthenticationInfo(user.getPkId(), user.getPassword(), getName());
            }
        }
        return null;
    }

    /**
     * 添加角色
     * @param userId
     * @param info
     */
    private void addRole(String userId, SimpleAuthorizationInfo info) {
        List<Role> roles = roleService.findRolesByUserId(userId);
        if(!ColUtil.isEmpty(roles)){
            for (Role role : roles) {
                info.addRole(role.getRoleName());
            }
        }
    }
}
